<?php

namespace App\Models;

use App\Http\Controllers\Home\CommonController;
use Illuminate\Database\Eloquent\Model;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;
use App\Easybitcoin;
class Currency extends BaseModel
{
    public $timestamps = false;

    protected $table = 'currency';

    protected  $guarded = [];


    public function getOne($where, $fileds = '*')
    {
        return $this->multiSelect($fileds)->multiWhere($where)->first();
    }

    /**
     * 按条件查询全部数据,根据配置显示条数显示
     */
    public function getList(array $where = [], $fields = '*', $order = '', $pageSize = '')
    {
        if ($pageSize) {
            return $this->multiSelect($fields)->multiWhere($where)->multiOrder($order)->paginate($pageSize);
        } else {
            return $this->multiSelect($fields)->multiWhere($where)->multiOrder($order)->get();
        }
    }

    public function getOneWithUser($where, $fileds = '*')
    {
        return $this->multiSelect($fileds)->with('currencyUser')->multiWhere($where)->first();
    }

    public function getSumWithUser($where, $field)
    {
        return $this->with('currencyUser')->multiWhere($where)->sum($field);
    }

    /**
     *插入数据
     */
    public function add($data)
    {
        return $this->_add($data);
    }


    /***
     * @param array $id
     * @param array $data
     * 更新数据
     */
    public function up($where, $data)
    {
        return $this->_updata($where, $data);
    }

    /**
     * @param $id
     * 删除数据
     */
    public function del($where)
    {
        return $this->_del($where);
    }

    public function currencyUser()
    {
        return $this->belongsTo('App\Models\CurrencyUser','currency_id','currency_id');
    }

    public function count($where=[], $field='')
    {
        return $this->multiWhere($where)->count($field);
    }

    public function sum($where=[], $field)
    {
        return $this->multiWhere($where)->sum($field);
    }


    /**
     * 图片操作
     */
    public function common()
    {
        $images = Input::file('currency_logo');//获取上传文件
        if ($images !== null) {
            $path = "upload/".date('Y-m-d',time())."/";//定义路径
            $imagesName = $images->getClientOriginalName();//获取上传图片文件名
            $extension = $images -> getClientOriginalExtension(); //获取上传图片的后缀名
            if (!in_array($extension,array('jpg','gif','png','jpeg'))) {
                $res['state'] = 400;
                $res['msg'] = '文件格式错误';
                return $res;
            }
            $fileName = str_random(8).'.'.$extension;//重命名
            $filePath = $images->move($path,$fileName); //使用move方法移动文件.
            return $filePath;
        }
        $filePath = '';
        return $filePath;
    }

    /**
     * 检测地址是否是有效地址
     *
     * @return boolean 如果成功返回个true
     * @return boolean 如果失败返回个false；
     *  @param unknown $url
     *  @param $port_number 端口号 来区分不同的钱包
     */

    private function check_qianbao_address($url,$currency){
        $bitcoin = new Easybitcoin($currency['rpc_user'],$currency['rpc_pwd'],$currency['rpc_url'],$currency['port_number']);
        $address = $bitcoin->validateaddress($url);
        if($address['isvalid']){
            return true;
        }else{
            return false;
        }
    }

    /**
     * 查询钱包余额
     * @param unknown $port_number 端口号
     * @return Ambigous <number, unknown> 剩余的余额
     */
    protected function get_qianbao_balance($currency){
        $bitcoin = new Easybitcoin($currency['rpc_user'],$currency['rpc_pwd'],$currency['rpc_url'],$currency['port_number']);
        $money = $bitcoin->getinfo();
        $num = empty($money['balance'])? 0:$money['balance'];
        return $num;
    }

    /**
     * 提币引用的方法
     * @param unknown $url 钱包地址
     * @param unknown $money 提币数量
     */
    private function qianbao_tibi($url,$money,$currency){
        $bitcoin = new Easybitcoin($currency['rpc_user'],$currency['rpc_pwd'],$currency['rpc_url'],$currency['port_number']);
        $bitcoin->walletlock();//强制上锁
        $bitcoin->walletpassphrase($currency['qianbao_key'],20);
        $id=$bitcoin->sendtoaddress($url,$money);
        $bitcoin->walletlock();
        return $id;
    }

    /**
     * 全站币种统计
     */
    public function get_currency_u_info()
    {
        $currency_u_info = DB::table('currency')
            ->join('currency_user','currency.currency_id','=','currency_user.currency_id')
            ->select(DB::raw("sum(xnb_currency_user.forzen_num) as forzen_num,sum(xnb_currency_user.num) as num"),"currency.currency_name")
            ->groupBy('currency.currency_id')
            ->get();
        return $currency_u_info;
    }


    /**
     * 获取币种
     */
    public function getCurrencyName()
    {
        $where = [];
        $fields = ['currency_id','currency_name'];
        $order['currency_id'] = 'desc';
        $pageSize = '';
        $data = $this->getList($where, $fields, $order, $pageSize)->toArray();
        return $data;
    }


    /**
     * 钱包币种管理--币种管理
     */
    public function get_index()
    {
        $result = Currency::paginate(3);
        foreach ($result as $k=>$v){
            $result[$k]['qianbao_balance'] = $this->get_qianbao_balance($v);
        }
        return $result;
    }

    /**
     * 设置涨停跌停价格
     */
    public function savePrice($request)
    {
        $currency_id = trim(intval($request['id']));
        if(empty($currency_id)){
            $res['status'] = -1;
            $res['msg'] = '参数错误';
            return $res;
        }
        if(!is_numeric($request['price_up']) || !is_numeric($request['price_down'])){
            $res['status'] = -2;
            $res['msg'] = '填写必须是数字';
            return $res;
        }
        $r[] = DB::table('currency')->where("currency_id",$currency_id)->update(['price_up' => $request['price_up']]);
        $r[] = DB::table('currency')->where("currency_id",$currency_id)->update(['price_down' => $request['price_down']]);
        if($r == false){
            $res['status'] = -3;
            $res['msg'] = '服务器繁忙,请稍后重试';
            return $res;
        }else{
            $res['status'] = 1;
            $res['msg'] = '修改成功';
            return $res;
        }
    }

    /**
     * 向会员钱包转账
     */
    public function get_set_member($request)
    {
        $cuid = intval($request["cuid"]);
        $currency = Currency::where('currency_id',$cuid)->first();
        $currency['qianbao_balance'] = $this->get_qianbao_balance($currency);
        return $currency;
    }

    public function set_member_qianbao($request)
    {
        $cuid = intval($request['cuid']);
        $username = $request['name'];//用户名
        $num = $request['num'];
        $currency = $this->get_set_member($request);
        if($request->isMethod('post')){
            $admin = Admin::where('admin_id',Session('admin_userid'))->first();
            if (md5($request['password']) != $admin['password']) {
                $this->error = "您输入的管理员密码错误!";
                return false;
            }

            $member = Member::where('email',$username)->first();
            if (empty($member)) {
                $this->error = "查无此人，请核实!";
                return false;
            }
            $qa = DB::table('qianbao_address')->where(['user_id'=>$member['member_id'], 'currency_id'=>$cuid])->first();
            if (empty($qa)) {
                $this->error = "暂无此用户信息，无法完成操作!";
                return false;
            }
            if (empty($qa->qianbao_url)){
                $this->error = "此用户未绑定提币地址，无法进行转账!";
                return false;
            }
            //判断看这个钱包地址是否是真实地址
            if(!$this->check_qianbao_address($qa->qianbao_url,$currency)){
                $this->error = "提币地址不是一个有效地址!";
                return false;
            }
            $num = floatval($num);
            $data['fee'] = 0;//手续费
            $data['currency_id'] = $cuid;
            $data['user_id'] = $qa->user_id;
            $data['url'] = $qa->qianbao_url;
            $data['name'] = $qa->name;
            $data['num'] = $num;
            $data['actual'] = $num;//实际到账价格
            $data['status'] = 0;
            $data['add_time'] = time();

            $tibi = $this->qianbao_tibi($qa->qianbao_url,$num,$currency);//提币程序

            if ($tibi) {
                //成功写入数据库
                $data['ti_id'] = $tibi;
                $re = DB::tabel('tibi')->insert($data);
                //减钱操作
//     			M("Currency_user")->where("member_id='{$_SESSION['USER_KEY_ID']}' and currency_id='$cuid'")->setDec("num",$num);
                $all = CurrencyUser::where(['member_id'=>$member['member_id'],'currency_id'=>$cuid])->first();
                $num_c = $all['num'] - $num;
                CurrencyUser::where(['member_id'=>$member['member_id'],'currency_id'=>$cuid])->update(['num'=>$num_c]);
                $this->error = "转账成功，请耐心等待!";
                return false;

            }else{
                //失败提示
                $this->error = "转账失败!";
                return false;
            }
        }

    }

    /**
     * 添加币种
     */
    public function addList($request)
    {
        if($request->isMethod('post')) {
            $images = Input::file('currency_logo');//获取上传文件
            if ($images !== null) {
                $path = "upload/" . date('Y-m-d', time()) . "/";//定义路径
                $extension = $images->getClientOriginalExtension(); //获取上传图片的后缀名
                if (!in_array($extension, array('jpg','gif', 'png', 'jpeg'))) {
                    $res['status'] = 400;
                    $res['msg'] = '图片格式错误';
                    return $res;
                }
                $fileName = str_random(8) . '.' . $extension;//重命名
                $filePath = $images->move($path, $fileName); //使用move方法移动文件.
                $data['currency_logo'] = '/'.$filePath;
            }
            $data['currency_name'] = $request['currency_name'];
            $data['currency_mark'] = $request['currency_mark'];
            $data['sort'] = $request['sort'];
            $data['currency_all_tibi'] = $request['currency_all_tibi'];
            $data['currency_all_num'] = $request['currency_all_num'];
            $data['currency_buy_fee'] = $request['currency_buy_fee'];
            $data['currency_sell_fee'] = $request['currency_sell_fee'];
            $data['currency_digit_num'] = $request['currency_digit_num'];
            $data['currency_url'] = $request['currency_url'];
            $data['rpc_user'] = $request['rpc_user'];
            $data['rpc_pwd'] = $request['rpc_pwd'];
            $data['rpc_url'] = $request['rpc_url'];
            $data['port_number'] = $request['port_number'];
            $data['qianbao_key'] = $request['qianbao_key'];
            $data['is_line'] = $request['is_line'];
            $data['is_lock'] = $request['is_lock'];
            $data['trade_currency_id'] = $request['trade_currency_id'];
            $data['detail_url'] = $request['detail_url'];
            $data['add_time'] = time();
            $result = $this->add($data);
            if ($result) {
                $res['status'] = 200;
                $res['msg'] = '操作成功！';
                return $res;
            }
            $res['status'] = 400;
            $res['msg'] = '操作失败！';
            return $res;
        }
    }

    /**
     * 币种的修改
     */
    public function editList($request)
    {
        $images = Input::file('currency_logo');//获取上传文件
        if ($images !== null) {
            $path = "upload/" . date('Y-m-d', time()) . "/";//定义路径
            $extension = $images->getClientOriginalExtension(); //获取上传图片的后缀名
            if (!in_array($extension, array('jpg','gif', 'png', 'jpeg'))) {
                $res['state'] = 400;
                $res['msg'] = '图片格式错误';
                return $res;
            }
            $fileName = str_random(8) . '.' . $extension;//重命名
            $filePath = $images->move($path, $fileName); //使用move方法移动文件.
            $data['currency_logo'] = '/'.$filePath;
        }
        $data['currency_name'] = $request['currency_name'];
        $data['currency_mark'] = $request['currency_mark'];
        $data['sort'] = $request['sort'];
        $data['currency_all_tibi'] = $request['currency_all_tibi'];
        $data['currency_all_num'] = $request['currency_all_num'];
        $data['currency_buy_fee'] = $request['currency_buy_fee'];
        $data['currency_sell_fee'] = $request['currency_sell_fee'];
        $data['currency_digit_num'] = $request['currency_digit_num'];
        $data['currency_url'] = $request['currency_url'];
        $data['rpc_user'] = $request['rpc_user'];
        $data['rpc_pwd'] = $request['rpc_pwd'];
        $data['rpc_url'] = $request['rpc_url'];
        $data['port_number'] = $request['port_number'];
        $data['qianbao_key'] = $request['qianbao_key'];
        $data['is_line'] = $request['is_line'];
        $data['is_lock'] = $request['is_lock'];
        $data['trade_currency_id'] = $request['trade_currency_id'];
        $data['detail_url'] = $request['detail_url'];
        $where['currency_id'] = $request['currency_id'];
        $result = $this->up($where,$data);
        if ($result) {
            $res['state'] = 200;
            $res['msg'] = '修改成功！';
            return $res;
        }
        $res['state'] = 400;
        $res['msg'] = '修改失败！';
        return $res;
    }


    //获取币种id,名称,标记信息
    public function getCurrencyAll()
    {

        $where = [];
        $fields = ['currency_id', 'currency_name', 'currency_mark'];
        $order['currency_id'] = 'asc';
        $pageSize = '';
        $data = $this->getList($where, $fields, $order, $pageSize)->toArray();
        return $data;
    }

    //获取币种所有信息
    public function getCurrencyAll2()
    {

        $where = [];
        $fields = '*';
        $order['currency_id'] = 'asc';
        $pageSize = '';
        $data = $this->getList($where, $fields, $order, $pageSize)->toArray();
        return $data;
    }

    /**

     * 根据id获取币种名称
     */
    public function getCurrencyNameById($currency_id)
    {
        if ($currency_id==0){
            return array('currency_name'=>'人民币','currency_mark'=>'CNY','currency_buy_fee'=>0,'currency_sell_fee'=>0);
        }

        $where['currency_id'] = $currency_id;
        $fields = ['currency_name,currency_mark,currency_buy_fee,currency_sell_fee'];
        $data = $this->getOne($where, $fields);
        if($data){
           $data = $data->toArray();
        }
        return $data;




    }

    //根据id获取币种数量
    public function getCurrencyNumByCurrencyId($currency,$where='')
    {
        $where['currency_id'] = $currency;
        $list = CurrencyUser::select(DB::raw('sum(num) as allnum,sum(forzen_num) as allcoldnum'))->groupBy('currency_id')->multiWhere($where)->first();

        //$list = array_map('get_object_vars', $list);
        //$list = $list[0];
        //dd($list);
        $list['currency'] = $this->getCurrencynameById($currency);
        return $list;

    }

    public function getCurrencyMemberNumByCurrencyId($currency,$where='')
    {
        $where['currency_id'] = $currency;
        $list = CurrencyUser::select(DB::raw('sum(num) as allnum,sum(forzen_num) as allcoldnum'))->groupBy('currency_id')->multiWhere($where)->first();

        //$list = array_map('get_object_vars', $list);
        $list['currency']=$this->getCurrencynameById($currency);
        return $list;

    }

    public function getCurrencyTibiByCurrencyId($currency,$where='')
    {
        $where['currency_id'] = $currency;

        $list['currency'] = $this->getCurrencynameById($currency);

        $data1 = Tibi::select(DB::raw('sum(num) as txmoney'))->groupBy('currency_id')->multiWhere($where)->where('status','=',1)->first();
        if($data1){
            $data1 = $data1->toArray();
        }
        //$data1 = array_map('get_object_vars', $data1);
//        if(!empty($data1)){
//            $list['txmoney'] = $data1[0];
//        }else{
//            $list['txmoney'] = 0;
//        }
        $list['txmoney'] = $data1;

        $data3 = Tibi::select(DB::raw('sum(num) as czmoney'))->groupBy('currency_id')->multiWhere($where)->where('status','=',3)->first();
        if($data3){
           $data3 = $data3->toArray();
        }

        $list['czmoney'] = $data3;
        $data0 = Trade::select(DB::raw('sum(num) as jymoney'))->groupBy('currency_id')->multiWhere($where)->where('status','=',0)->first();
        if($data0){
            $data0 = $data0->toArray();
        }
        $list['jymoney'] = $data0;
        return $list;
    }

    public function currency()
    {
        return $this->hasOne('App\Models\Currency','currency_id','trade_currency_id');
    }

    /**
     *
     * @param int $currency_id 币种id
     * @return array 币种结果集
     */
    public function getCurrencyByCurrencyId($currency_id = 0)
    {
        if (!$currency_id) {
            $where['currency_id'] = ['>', $currency_id];
        } else {
            $where['currency_id'] = $currency_id;
        }
        //获取交易币种信息
        $list = $this->with('currency')->withCertain('currency',['currency_id','currency_name'])->multiWhere($where)->get();
        if ($list) {
            return $list;
        } else {
            return false;
        }
    }

}
